/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.syncope.ide.netbeans.view;

import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import org.apache.commons.lang3.StringUtils;
import org.openide.util.NbPreferences;

public class ServerDetailsView extends JDialog {

    private static final long serialVersionUID = -8693554903195406915L;

    public static final Logger LOG = Logger.getLogger("ServerDetailsView");

    /**
     * Creates new form LoginView
     *
     * @param parent Parent Frame
     * @param modal Whether it is modal or not
     */
    public ServerDetailsView(final java.awt.Frame parent, final boolean modal) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(this);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    //CHECKSTYLE:OFF
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new JLabel();
        jLabel2 = new JLabel();
        jLabel3 = new JLabel();
        schemeTxt = new JTextField();
        userNameTxt = new JTextField();
        passwordTxt = new JPasswordField();
        okButton = new JButton();
        jLabel4 = new JLabel();
        hostTxt = new JTextField();
        jLabel5 = new JLabel();
        portTxt = new JTextField();
        jLabel6 = new JLabel();

        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setLabelFor(schemeTxt);
        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, "Scheme");
        jLabel1.setToolTipText("");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, "Username");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, "Password");
        jLabel3.setToolTipText("");

        schemeTxt.setToolTipText("");

        org.openide.awt.Mnemonics.setLocalizedText(okButton, "submit");
        okButton.addActionListener(this::okButtonActionPerformed);

        jLabel4.setHorizontalAlignment(SwingConstants.CENTER);
        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, "Apache Syncope connection");
        jLabel4.setToolTipText("");

        hostTxt.setToolTipText("");

        jLabel5.setLabelFor(portTxt);
        org.openide.awt.Mnemonics.setLocalizedText(jLabel5, "Port");
        jLabel5.setToolTipText("");

        jLabel6.setLabelFor(hostTxt);
        org.openide.awt.Mnemonics.setLocalizedText(jLabel6, "Host");
        jLabel6.setToolTipText("");

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4, GroupLayout.PREFERRED_SIZE,
                        256, GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                        .addComponent(okButton, GroupLayout.PREFERRED_SIZE,
                            74, GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1)
                                .addComponent(jLabel2)
                                .addComponent(jLabel3)
                                .addComponent(jLabel5)
                                .addComponent(jLabel6))
                            .addGap(39, 39, 39)
                            .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
                                .addComponent(portTxt)
                                .addComponent(hostTxt)
                                .addComponent(userNameTxt)
                                .addComponent(schemeTxt)
                                .addComponent(passwordTxt, GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE)))))
                .addContainerGap(40, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel4, GroupLayout.PREFERRED_SIZE, 65, GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(schemeTxt, GroupLayout.PREFERRED_SIZE,
                        GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(hostTxt, GroupLayout.PREFERRED_SIZE,
                        GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(portTxt, GroupLayout.PREFERRED_SIZE,
                        GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(userNameTxt, GroupLayout.PREFERRED_SIZE,
                        GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(passwordTxt, GroupLayout.PREFERRED_SIZE,
                        GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(okButton)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    //CHECKSTYLE:ON

    protected void okButtonActionPerformed(final java.awt.event.ActionEvent evt) {
        // validation
        List<String> validation = validate(schemeTxt, hostTxt, portTxt, userNameTxt);
        if (validation.isEmpty()) {
            Preferences prefs = NbPreferences.forModule(ResourceExplorerTopComponent.class);
            prefs.put("scheme", schemeTxt.getText());
            prefs.put("host", hostTxt.getText());
            prefs.put("port", portTxt.getText());
            prefs.put("username", userNameTxt.getText());
            prefs.put("password", new String(passwordTxt.getPassword()));
            // dismiss panel
            this.dispose();
        } else {
            JOptionPane.showMessageDialog(
                    null, "Please insert valid " + validation, "Validation  Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void setDetails(
            final String scheme,
            final String host,
            final String port,
            final String username,
            final String password) {
        schemeTxt.setText(scheme);
        hostTxt.setText(host);
        portTxt.setText(port);
        userNameTxt.setText(username);
        passwordTxt.setText(password);
    }

    public static void main(final String[] args) {
        /* Create and display the dialog */
        EventQueue.invokeLater(() -> {
            ServerDetailsView dialog = new ServerDetailsView(new JFrame(), true);
            dialog.addWindowListener(new WindowAdapter() {

                @Override
                public void windowClosing(final WindowEvent e) {
                    System.exit(0);
                }
            });
            dialog.setVisible(true);
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private JTextField hostTxt;
    private JLabel jLabel1;
    private JLabel jLabel2;
    private JLabel jLabel3;
    private JLabel jLabel4;
    private JLabel jLabel5;
    private JLabel jLabel6;
    private JButton okButton;
    private JPasswordField passwordTxt;
    private JTextField portTxt;
    private JTextField schemeTxt;
    private JTextField userNameTxt;
    // End of variables declaration//GEN-END:variables

    private static List<String> validate(
        final JTextField schemeTxt,
        final JTextField hostTxt,
        final JTextField portTxt,
        final JTextField userNameTxt) {

        List<String> res = new ArrayList<>();

        if (StringUtils.isBlank(schemeTxt.getText())
                || (!StringUtils.equals(schemeTxt.getText(), "http")
                && !StringUtils.equals(schemeTxt.getText(), "https"))) {
            res.add("scheme");
        }
        if (StringUtils.isBlank(hostTxt.getText())) {
            res.add("host");
        }
        if (StringUtils.isBlank(portTxt.getText()) || !StringUtils.isNumeric(portTxt.getText())) {
            res.add("port");
        }
        if (StringUtils.isBlank(userNameTxt.getText())) {
            res.add("username");
        }
        return res;
    }
}
